package es.us.lsi.daw.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import es.us.lsi.daw.dao.DAOAuthentication;
import es.us.lsi.daw.model.security.User;
import es.us.lsi.daw.model.security.WebUser;

@Component
@Transactional
//TODO(mamuso) Should this reside in ModelSecurity?
public class DAOAuthenticationImpl extends DAOComunImpl implements DAOAuthentication {
	
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User result = null;
		Criteria crit = sessionFactory.getCurrentSession().createCriteria(User.class);
		crit.add(Restrictions.eq(User.A_USERNAME, username));
		result = (User) crit.uniqueResult();
		return result;
	}

	public User getCurrentUser(){
		String username = this.getCurrentUsername();
		WebUser result = null;
		Criteria c1 = sessionFactory.getCurrentSession().createCriteria(WebUser.class);
		c1.add(Restrictions.eq(User.A_USERNAME, username));
		result = (WebUser)c1.uniqueResult();
		if(result == null){
			//IMPROVE Manage authentication exceptions in the way you want
			 throw new RuntimeException("User not present as WebUser");
		}
		return result;
	}
	
}
